import { createStore } from 'vuex';
import axios from 'axios'
const store = createStore({
  state() {
    return {
      goodsInf: [],
      foodInf: [],
      carInf: [],
      // 头部
      sellerInf: {},
      // 总价
      plusPrice: 0,
      ratingArr:[]
    }
  },
  mutations: {
    update(state, payload) {
      state.goodsInf = payload.result;
      // console.log(state.goodsInf);
    },
    update2(state, payload) {
      state.foodInf = payload;
    },
    updateSeller(state, payload) {
      state.sellerInf = payload.seller;
      // console.log('--------', payload);
    },
    ratingData(state,payload){
      state.ratingArr=payload.ratingData
      console.log('ratingData', state.ratingArr)
    },
    add(state, index) {
      if (!state.foodInf[index].num ) {
        state.foodInf[index].num = 1;
        console.warn(state.foodInf[index])
        state.carInf.push(state.foodInf[index]);
        state.plusPrice += state.foodInf[index].price;
      } else if (state.foodInf[index].num !== undefined) {
        state.foodInf[index].num++;
        let sum = 0;
        state.carInf.forEach((item) => {
          sum += item.price * item.num;
        })
        state.plusPrice = sum;
      }
    },

    minus(state, index) {
      if (state.foodInf[index].num === 0) {
        state.carInf.splice(index, 1)
      } else if (state.foodInf[index].num !== 0) {
        state.foodInf[index].num--
        state.plusPrice-=state.foodInf[index].price
      }
    },

    clear(state){
      state.carInf='';
      state.plusPrice=0;
      console.log('清空',state.goodsInf)
      state.goodsInf.forEach((item)=>{
        item.foods.forEach((foodsNum)=>{
          console.log('11111',foodsNum)
         if(foodsNum.num!==0){
            foodsNum.num=0
           }
        })
      })
    }
  },
  getters: {

  },
  actions: {
    async getGoods(context, name) {
      const result = await axios.get('http://localhost:8000/goods')
      console.log('result',result)
      context.commit('update', {
        result: result.data.goods
      })
      // console.warn("@@@", result.data.goods)
      result.data.goods.forEach(item => {
        if (item.name === name) {
          context.commit('update2', item.foods)
        }
      })
    },

    async getSeller({ commit }) {
      const { data: { data } } = await axios.get('http://localhost:8000/seller')
      // console.log("--------", data)
      commit('updateSeller', {
        seller: data
      })
    },

    async getRating({commit}){
      const ratingData=await axios.get('http://localhost:8000/rating')
      console.log('rating',ratingData)
      commit('ratingData',{
        ratingData:ratingData.data
      })
    }
  }
})

export default store;